package com.qyhl.webtv.module_circle.circle.msg.chat;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.avos.avoscloud.im.v2.AVIMClient;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.callback.AVIMClientCallback;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.qyhl.webtv.basiclib.utils.DESedeUtil;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.entity.circle.ShieldResultBean;
import com.qyhl.webtv.module_circle.R;
import com.qyhl.webtv.module_circle.R2;
import com.qyhl.webtv.module_circle.common.CircleUrl;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import cn.leancloud.chatkit.LCChatKit;
import cn.leancloud.chatkit.adapter.LCIMCommonListAdapter;
import cn.leancloud.chatkit.cache.LCIMConversationItemCache;
import cn.leancloud.chatkit.event.LCIMClickMessageEvent;
import cn.leancloud.chatkit.event.LCIMConversationItemLongClickEvent;
import cn.leancloud.chatkit.event.LCIMIMTypeMessageEvent;
import cn.leancloud.chatkit.event.LCIMOfflineMessageCountChangeEvent;
import cn.leancloud.chatkit.utils.LCIMConstants;
import cn.leancloud.chatkit.viewholder.LCIMConversationItemHolder;
import es.dmoral.toasty.Toasty;

/**
 * 私信消息
 *
 * @author helin
 */
public class ChatMessageFragment extends Fragment {


    protected SwipeRefreshLayout refreshLayout;
    protected RecyclerView recyclerView;

    protected LCIMCommonListAdapter<AVIMConversation> itemAdapter;
    protected LinearLayoutManager layoutManager;
    protected RelativeLayout emptyLayout;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(cn.leancloud.chatkit.R.layout.lcim_conversation_list_fragment, container, false);

        refreshLayout = (SwipeRefreshLayout) view.findViewById(cn.leancloud.chatkit.R.id.fragment_conversation_srl_pullrefresh);
        recyclerView = (RecyclerView) view.findViewById(cn.leancloud.chatkit.R.id.fragment_conversation_srl_view);
        emptyLayout = (RelativeLayout) view.findViewById(cn.leancloud.chatkit.R.id.empty_layout);

        refreshLayout.setEnabled(false);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.addItemDecoration(new RecycleViewDivider(
                this.getActivity(), LinearLayoutManager.HORIZONTAL, 1, ContextCompat.getColor(this.getContext(), R.color.global_gray_lv3)));

        itemAdapter = new LCIMCommonListAdapter<>(LCIMConversationItemHolder.class);
        recyclerView.setAdapter(itemAdapter);
        EventBus.getDefault().register(this);
        mIsPrepared = true;
        lazyLoad();
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        updateConversationList();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateConversationList();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }


    /**
     * 收到对方消息时响应此事件
     *
     * @param event
     */
    @Subscribe
    public void onEvent(LCIMIMTypeMessageEvent event) {
        updateConversationList();
    }

    /**
     * 删除会话列表中的某个 item
     *
     * @param event
     */
    @Subscribe
    public void onEvent(LCIMConversationItemLongClickEvent event) {
        if (null != event.conversation) {
            String conversationId = event.conversation.getConversationId();
            LCIMConversationItemCache.getInstance().deleteConversation(conversationId);
            updateConversationList();
        }
    }

    /**
     * item点击事件
     *
     * @param event
     */
    @Subscribe
    public void onEvent(final LCIMClickMessageEvent event) {
        if (null != event.conversation) {

            String dstusername = "";
            String userName = CommonUtils.getInstance().getUserName();
            for (int i = 0; i < event.conversation.getMembers().size(); i++) {
                if (!event.conversation.getMembers().get(i).equals(userName)) {
                    dstusername = event.conversation.getMembers().get(i);
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String time = sdf.format(new Date());
            String code = "Z5" + time + "I2863";
            String url = CircleUrl.CIRCLE_URL + "?timestamp=" + time;
            String userNameS = CommonUtils.getInstance().getUserName();

            EasyHttp.post(url)
                    .upBytes(DESedeUtil.encryptMode(code, "siteId=" + CommonUtils.getInstance().getSite()+ "&method=mailPermit" + "&username=" + userNameS
                            + "&dstUsername=" + dstusername))
                    .isDecrypt(true)
                    .decryptKet(code)
                    .execute(new SimpleCallBack<ShieldResultBean>() {
                        @Override
                        public void onError(ApiException e) {
                            Toasty.normal(getContext(), "解析异常，稍后再试！").show();
                        }

                        @Override
                        public void onSuccess(ShieldResultBean shieldResultBean) {
                            if (shieldResultBean.isDefriend()) {
                                Toasty.normal(getContext(), "对不起，对方拒绝和你聊天！").show();
                            } else if (shieldResultBean.isGag()) {
                                Toasty.normal(getContext(), "对不起，管理员禁言了你！").show();
                            } else {
                                try {
                                    Intent intent = new Intent();
                                    intent.setPackage(getContext().getPackageName());
                                    intent.setAction(LCIMConstants.CONVERSATION_ITEM_CLICK_ACTION);
                                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                                    intent.putExtra(LCIMConstants.CONVERSATION_ID, event.conversation.getConversationId());
                                    getContext().startActivity(intent);
                                } catch (ActivityNotFoundException exception) {
                                    Log.i(LCIMConstants.LCIM_LOG_TAG, exception.toString());
                                }
                            }
                        }
                    });

        }
    }

    /**
     * 刷新页面
     */
    private void updateConversationList() {
        List<String> convIdList = LCIMConversationItemCache.getInstance().getSortedConversationList();
        List<AVIMConversation> conversationList = new ArrayList<>();
        if (convIdList == null || convIdList.size() < 1) {
            emptyLayout.setVisibility(View.VISIBLE);
        }else{
            emptyLayout.setVisibility(View.GONE);
        }
        for (String convId : convIdList) {
            conversationList.add(LCChatKit.getInstance().getClient().getConversation(convId));
        }

        itemAdapter.setDataList(conversationList);
        itemAdapter.notifyDataSetChanged();

    }

    /**
     * 离线消息数量发生变化是响应此事件
     * 避免登陆后先进入此页面，然后才收到离线消息数量的通知导致的页面不刷新的问题
     *
     * @param updateEvent
     */
    @Subscribe
    public void onEvent(LCIMOfflineMessageCountChangeEvent updateEvent) {
        updateConversationList();
    }


    /**
     * 会话列表
     */
    @BindView(R2.id.fragment_conversation_srl_view)
    RecyclerView mConversationSrlView;
    /**
     * 下拉刷新
     */
    @BindView(R2.id.fragment_conversation_srl_pullrefresh)
    SwipeRefreshLayout mConversationSrlPullrefresh;

    /**
     * 数据是否第一次加载
     */
    private boolean mIsInited;
    /**
     * 布局界面初始化
     */
    private boolean mIsPrepared;

    public ChatMessageFragment() {
    }

    public static ChatMessageFragment newInstance() {
        return new ChatMessageFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            lazyLoad();
        }
    }

    /**
     * 懒加载数据
     */
    public void lazyLoad() {
        if (getUserVisibleHint() && mIsPrepared && !mIsInited) {
            //异步初始化，在初始化后显示正常UI
            loadData();
        }
    }

    /**
     * 加载数据
     */
    private void loadData() {
        mIsInited = true;

        if (null == LCChatKit.getInstance().getClient()) {
            //用户登陆
            String userName = CommonUtils.getInstance().getUserName();
            LCChatKit.getInstance().open(userName, new AVIMClientCallback() {
                @Override
                public void done(AVIMClient avimClient, AVIMException e) {
                    if (null == e) {
                        updateConversationList();
                    } else {
                        Toasty.normal(getActivity(),"服务器异常").show();
                    }
                }
            });
        } else {
            updateConversationList();
        }


    }


}
